'''
全民运动意外保险产品计划
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product,combinations
import json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "全民运动意外保险产品计划"

    # 生成产品信息
    def genProductInfo(self):

        expires  =["一天","三天","七天","十四天","三十天","一年"]
        sports = []


        for v in (  self.getResult() ):

            if len(v) == 0:

                continue

            sports.append("".join( v ))

            for x in product( sports,expires):

                introduce = {

                    "跑步意外保障（含马拉松赛事）":{
                        "意外身故/残疾":"50000元",
                        "意外医疗":"1000元"
                    },
                    "健身房意外保障":{
                        "意外身故/残疾": "50000元",
                        "意外医疗": "1000元"
                    },
                    "潜水意外保障（含游泳）":{
                        "意外身故/残疾": "50000元",
                        "意外医疗": "1000元"
                    },
                    "登山意外保障":{
                        "意外身故/残疾": "50000元",
                        "意外医疗": "1000元"
                    },
                    "滑雪意外保障":{
                        "意外身故/残疾": "50000元",
                        "意外医疗": "1000元"
                    },
                }

                introduce = "'" + json.dumps( introduce,ensure_ascii=False) + "'"

                print( domain[self.name]["insert_sql"].format( x[0],x[1],introduce) )
                # 写入数据库
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( x[0],x[1],introduce))
                self.mysql._conn.commit()
                print("%s产品信息写入数据库成功"%self.name )

    # 执行爬虫
    def requestJson(self,dt=None):

        data = {

            "跑步": "QMJSYWX_MLSSGCJ",
            "健身房": "QMJSYWX_JSFSGCJ",
            "登山": "QMJSYWX_DSSGCJ",
            "滑雪": "QMJSYWX_HXSGCJ",
            "潜水(游泳)": "QMJSYWX_QSSGCJ"
        }

        sports = dt["sport"].split("/")

        # 移除空元素
        sports.remove("")

        print( sports )

        if dt["expire"] == "一天":

            print("expire one days")

            price = 0.9

            for x in sports:

                val = data[x]

                price += float( self.factorySport()[0][val] )

            price = Helper.decimalParse( price )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        elif dt["expire"] == "三天":

            print("expire 3 days")

            price = 2.5
            for x in sports:

                val = data[x]

                price += float(self.factorySport()[1][val])

            price = Helper.decimalParse(price)

            data = {

                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            self.mysql.updatePrice(data)

        elif dt["expire"] == "七天":
            print("expire 7 days")
            price = 4.8
            for x in sports:
                val = data[x]

                price += float(self.factorySport()[2][val])

            price = Helper.decimalParse(price)

            data = {

                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            self.mysql.updatePrice(data)

        elif dt["expire"] == "十四天":

            print("expire 14 days")
            price = 7.7

            for x in sports:

                val = data[x]

                price += float(self.factorySport()[3][val])

            price = Helper.decimalParse(price)

            data = {

                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            self.mysql.updatePrice(data)

        elif dt["expire"] == "三十天":
            print("expire 30 days")
            price = 11.3
            for x in sports:

                val = data[x]

                price += float(self.factorySport()[4][val])

            price = Helper.decimalParse(price)

            data = {

                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            self.mysql.updatePrice(data)

        elif dt["expire"] == "一年":

            print("expire a year")
            price = 55.8

            for x in sports:

                val = data[x]

                price += float(self.factorySport()[5][val])

            price = Helper.decimalParse(price)

            data = {

                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            self.mysql.updatePrice(data)

    # 匹配运动项目
    def factorySport(self,length=None):

        str = {
            "strs": [
                {"QMJSYWX_JCSGCJ": "0.9", "QMJSYWX_MLSSGCJ": "0.5", "QMJSYWX_JSFSGCJ": "0.5", "QMJSYWX_DSSGCJ": "1.3",
                 "QMJSYWX_HXSGCJ": "1.3", "QMJSYWX_QSSGCJ": "1.3"},
                {"QMJSYWX_JCSGCJ": "2.5", "QMJSYWX_MLSSGCJ": "1.5", "QMJSYWX_JSFSGCJ": "1.5", "QMJSYWX_DSSGCJ": "3",
                 "QMJSYWX_HXSGCJ": "3", "QMJSYWX_QSSGCJ": "3"},
                {"QMJSYWX_JCSGCJ": "4.8", "QMJSYWX_MLSSGCJ": "3.1", "QMJSYWX_JSFSGCJ": "3.1", "QMJSYWX_DSSGCJ": "6.1",
                 "QMJSYWX_HXSGCJ": "6.1", "QMJSYWX_QSSGCJ": "6.1"},
                {"QMJSYWX_JCSGCJ": "7.7", "QMJSYWX_MLSSGCJ": "4.4", "QMJSYWX_JSFSGCJ": "4.4", "QMJSYWX_DSSGCJ": "10.4",
                 "QMJSYWX_HXSGCJ": "10.4", "QMJSYWX_QSSGCJ": "10.4"},
                {"QMJSYWX_JCSGCJ": "11.3", "QMJSYWX_MLSSGCJ": "8.2", "QMJSYWX_JSFSGCJ": "8.2", "QMJSYWX_DSSGCJ": "15.2",
                 "QMJSYWX_HXSGCJ": "15.2", "QMJSYWX_QSSGCJ": "15.2"},
                {"QMJSYWX_JCSGCJ": "55.8", "QMJSYWX_MLSSGCJ": "35.5", "QMJSYWX_JSFSGCJ": "35.5",
                 "QMJSYWX_DSSGCJ": "74.5", "QMJSYWX_HXSGCJ": "74.5", "QMJSYWX_QSSGCJ": "74.5"}
            ]
        }

        calc = str["strs"]
        # 保障期限 一天
        return calc

    '''根据n获得列表中的所有可能组合（n个元素为一组）'''
    def combine(self,temp_list,n):

        temp_list2 = []

        for c in combinations(temp_list, n):

            temp_list2.append(c)

        return temp_list2

    # 获取组合数据
    def getResult(self):

        list1 = ["跑步/", "健身房/", "登山/", "滑雪/", "潜水(游泳)/"]

        end_list = []

        for i in range(len(list1)+1):

            end_list.extend(self.combine(list1, i))


        return end_list

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)










